from typing import Any

from dify_plugin import ToolProvider
from dify_plugin.errors.tool import ToolProviderCredentialValidationError

from ksai.database.executor import DatabaseExecutor, driver_mapping
from ksai.utils.strings import has_text


class KsaiDifyPluginAuthorizedDbProvider(ToolProvider):
    def _validate_credentials(self, credentials: dict[str, Any]) -> None:
        try:
            for param in ['type', 'port', 'username', 'password', 'database']:
                if param not in credentials or has_text(credentials.get(param, "")) is False:
                    raise ValueError(f"Parameter {param} is required")

            database_type = credentials.get('type')
            if has_text(driver_mapping.get(database_type)) is False:
                raise ValueError(f"Database type {database_type} is not supported")

            executor = DatabaseExecutor.create_from_config(credentials)
            executor.test_connection()

        except Exception as e:
            raise ToolProviderCredentialValidationError(str(e))
